define(['jquery', 'bootstrap', 'backend', 'table', 'form','layui'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/goods/index' + location.search,
                    add_url: 'goods/goods/add',
                    edit_url: 'goods/goods/edit',
                    del_url: 'goods/goods/del',
                    multi_url: 'goods/goods/multi',
                    table: 'goods',
                }
            });

            //编辑框 双击 按钮 方式 出现弹出框 最大显示
            Table.button.edit.extend += ' data-area=["100%","100%"]';
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'bn', title: __('Bn'), operate:'LIKE'},
                        {field: 'name', title: __('Name'), operate:'LIKE'},
                        {field: 'price', title: __('Price'), operate:'BETWEEN'},
                        {field: 'image', title: __('Image'), events: Table.api.events.image, formatter: Table.api.formatter.image,searchable:false},
                        {field: 'category.name', title: __('Category_id'), operate:'LIKE'},
                        {field: 'goodstype.name', title: __('Goods_type_id'), operate:'LIKE'},
                        {field: 'brand.name', title: __('Brand_id'), operate:'LIKE'},
                        {field: 'is_nomal_virtual', title: __('Is_nomal_virtual'), searchList: Config.isNormalVirtual, table: table, formatter: Table.api.formatter.lable},
                        {field: 'market_switch', title: __('Market_switch'), searchList: {"1":__('Yes'),"0":__('No')}, table: table, formatter: Table.api.formatter.toggle},
                        {field: 'top_switch', title: __('Top_switch'), searchList: {"1":__('Yes'),"0":__('No')}, table: table, formatter: Table.api.formatter.toggle},
                        {field: 'stock', title: __('Stock'),searchable:false},
                        {field: 'freeze_stock', title: __('Freeze_stock'),searchable:false},
                        {field: 'weigh', title: __('Weigh')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'goods/goods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'goods/goods/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'goods/goods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            $(document).on("change", "#c-goods_type_id", function () {

                layer.confirm('更换类型后，货品需重新生成，确定要更换吗？', {
                    btn: ['确定', '取消'],
                    title: '提示',
                }, function(index) {
                    layer.close(index);
                    Fast.api.ajax({
                        url: 'goods/goods/getSpec',
                        data: {
                            type_id: $('#c-goods_type_id').val()
                        }
                    }, function (data, ret) {
                        $("#product-info").html(ret.data);
                    }, function (data, ret) {
                        Layer.alert(ret.msg);
                        return false;
                    });

                }, function() {});
            })

            $("body").on("click", "#open_spec", function() {
                var is_open = $(this).attr("is_open");
                if (is_open == 'false') {
                    $("input[name=open_spec]").val("1");
                    $("#spec_select").show();
                    $("#no_spec").hide();
                    $(this).html(__('Close'));
                    $(this).attr("is_open", "true");
                } else {
                    $("input[name=open_spec]").val("0");
                    $("#spec_select").hide();
                    $("#no_spec").show();
                    $(this).html(__('Open'));
                    $(this).attr("is_open", "false");
                }
            });

            $("body").on("click", ".generate-spec", function() {
                var list = $('#spec_select input[type=checkbox]:checked');
                if (list.length > 0) {

                    //提交部分form 数据 begin
                    var a = $(this);
                    var section = a.closest('.section');
                    var f = $('<form></form>'),
                        newForm = section.clone();
                    f.append(newForm);
                    var sectionData = f.serialize();
                    //提交部分form 数据 end

                    Fast.api.ajax({
                        url: 'goods/goods/getSpecHtml',
                        data: sectionData
                    }, function (data, ret) {
                        console.log(ret)
                        $("#more_spec").html(ret.data);
                    }, function (data, ret) {
                        Layer.alert(ret.msg);
                        return false;
                    });
                } else {
                    layer.msg("请选择属性");
                    return false;
                }
                return false;
            });
            //删除行规格
            $("body").on("click", ".del-class", function() {
                $(this).parent().parent('tr').remove();
            });

            $("body").on("click", ".isdefalut", function() {

                if($(this).prop("checked")){
                    var checkedName = $(this).attr("name");
                    $(".isdefalut").each(function (i,dom) {
                        var name = $(dom).attr("name");
                        if(name != checkedName){
                            $(dom).attr("checked",false);
                            $(dom).attr("value","0");
                            //$("#more_spec .layui-form-checkbox").removeClass('layui-form-checked');
                        }else {
                            $(dom).attr("checked", true);
                            $(dom).attr("value","1");
                        }
                    });
                    //$(this).addClass("layui-form-checked");
                }else{
                    $(".isdefalut").each(function (i,dom) {
                        if (i == 0){
                            $(dom).prop("checked", true);
                            $(dom).prop("value","1");
                            return false;
                        }
                    });
                }
            });

            //选择图片
            $("body").on('click', '.upSpecImage', function (e) {

                var multiple = false;
                var mimetype = 'image';
                var admin_id = '';
                var user_id = '';

                //获取
                var specImageTd = $(this).parent().find(".spec_image");

                Fast.api.open("general/attachment/select?element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype=" + mimetype + "&admin_id=" + admin_id + "&user_id=" + user_id, __('Choose'), {
                    callback: function (data) {

                        console.log(specImageTd)
                        specImageTd.find('img').attr('src',data.url);
                        specImageTd.find('input').val(data.url);
                        specImageTd.show();
                    }
                });

            });
            // 删除规格图片
            $("body").on("click", ".del-img", function () {
                var specImageDiv =  $(this).parent().parent();
                specImageDiv.find('img').attr('src','');
                specImageDiv.find('input').val('');
                specImageDiv.hide();
            })
            Controller.api.bindevent();
        },
        edit: function () {
            $(document).on("change", "#c-goods_type_id", function () {

                layer.confirm('更换类型后，货品需重新生成，确定要更换吗？', {
                    btn: ['确定', '取消'],
                    title: '提示',
                }, function(index) {
                    layer.close(index);
                    Fast.api.ajax({
                        url: 'goods/goods/getSpec',
                        data: {
                            type_id: $('#c-goods_type_id').val()
                        }
                    }, function (data, ret) {
                        $("#product-info").html(ret.data);
                    }, function (data, ret) {
                        Layer.alert(ret.msg);
                        return false;
                    });

                }, function() {});
            })

            $("body").on("click", "#open_spec", function() {
                var is_open = $(this).attr("is_open");
                if (is_open == 'false') {
                    $("input[name=open_spec]").val("1");
                    $("#spec_select").show();
                    $("#no_spec").hide();
                    $(this).html(__('Close'));
                    $(this).attr("is_open", "true");
                } else {
                    $("input[name=open_spec]").val("0");
                    $("#spec_select").hide();
                    $("#no_spec").show();
                    $(this).html(__('Open'));
                    $(this).attr("is_open", "false");
                }
            });

            $("body").on("click", ".generate-spec", function() {
                var list = $('#spec_select input[type=checkbox]:checked');
                if (list.length > 0) {

                    //提交部分form 数据 begin
                    var a = $(this);
                    var section = a.closest('.section');
                    var f = $('<form></form>'),
                        newForm = section.clone();
                    f.append(newForm);
                    var sectionData = f.serialize();
                    //提交部分form 数据 end

                    Fast.api.ajax({
                        url: 'goods/goods/getSpecHtml',
                        data: sectionData
                    }, function (data, ret) {
                        console.log(ret)
                        $("#more_spec").html(ret.data);
                    }, function (data, ret) {
                        Layer.alert(ret.msg);
                        return false;
                    });
                } else {
                    layer.msg("请选择属性");
                    return false;
                }
                return false;
            });
            //删除行规格
            $("body").on("click", ".del-class", function() {
                $(this).parent().parent('tr').remove();
            });

            $("body").on("click", ".isdefalut", function() {

                if($(this).prop("checked")){
                    var checkedName = $(this).attr("name");
                    $(".isdefalut").each(function (i,dom) {
                        var name = $(dom).attr("name");
                        if(name != checkedName){
                            $(dom).attr("checked",false);
                            $(dom).attr("value","0");
                            //$("#more_spec .layui-form-checkbox").removeClass('layui-form-checked');
                        }else {
                            $(dom).attr("checked", true);
                            $(dom).attr("value","1");
                        }
                    });
                    //$(this).addClass("layui-form-checked");
                }else{
                    $(".isdefalut").each(function (i,dom) {
                        if (i == 0){
                            $(dom).prop("checked", true);
                            $(dom).prop("value","1");
                            return false;
                        }
                    });
                }
            });

            //选择图片
            $("body").on('click', '.upSpecImage', function (e) {

                var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
                var mimetype = $(this).data("mimetype") ? $(this).data("mimetype") : '';
                var admin_id = $(this).data("admin-id") ? $(this).data("admin-id") : '';
                var user_id = $(this).data("user-id") ? $(this).data("user-id") : '';

                //获取
                var specImageTd = $(this).parent().find(".spec_image");

                Fast.api.open("general/attachment/select?element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype=" + mimetype + "&admin_id=" + admin_id + "&user_id=" + user_id, __('Choose'), {
                    callback: function (data) {

                        console.log(specImageTd)
                        specImageTd.find('img').attr('src',data.url);
                        specImageTd.find('input').val(data.url);
                        specImageTd.show();
                    }
                });

            });
            // 删除规格图片
            $("body").on("click", ".del-img", function () {
                var specImageDiv =  $(this).parent().parent();
                specImageDiv.find('img').attr('src','');
                specImageDiv.find('input').val('');
                specImageDiv.hide();
            })
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});